package com.woniu.exception;

import com.woniu.common.CommonResult;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(UnauthorizedException.class)
    public String unauthorizedExceptionHandler(UnauthorizedException e){
        e.printStackTrace();
        return "/403";//跳转到  403.html
    }


    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public String httpRequestMethodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException e){
        e.printStackTrace();
        return "访问方式不支持";
    }


    /*@ExceptionHandler(LoginException.class)
    @ResponseBody
    public CommonResult loginExceptionHandler(LoginException e){
        return CommonResult.failed(e.getMessage());
    }*/

   /* @ExceptionHandler(BindException.class)
    @ResponseBody
    public CommonResult bindExceionHandler(BindException e){
        e.printStackTrace();
        BindingResult result = e.getBindingResult();//BindingResult对象存放了Spring校验抛出的异常
        List<FieldError> list = result.getFieldErrors();
        for (FieldError fieldError : list) {
            String msg = fieldError.getDefaultMessage();
            return CommonResult.valetateFailed(msg);
        }
        return CommonResult.valetateFailed();
    }*/

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonResult exceptionHandler(Exception e){
        e.printStackTrace();
        System.out.println(e.getClass().getName());
        return CommonResult.failed("网络异常");
    }
}
